import { getToken, removeToken, setToken } from '@/utils/auth.js'
import { sysLogin, sysProfile, sysUser } from '@/api/user.js'
import { Message } from 'element-ui'
const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  // 获取用户信息
  setUserInfo(state, value) {
    state.userInfo = value
  },
  // 清除用户信息和token
  logout(state) {
    state.userInfo = ''
    state.token = ''
    setToken('')
  }
}
const actions = {
  // 登录以及token储存
  async toLogin(store, form) {
    const res = await sysLogin(form)
    try {
      store.commit('setToken', res.data)
    } catch (error) {
      Message.error(res.message)
      return Promise.reject(res.message)
    }
  },
  // 获取用户信息并存储
  async getUserInfo({ commit }) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    // 调用方法存储
    const res3 = Object.assign({}, res.data, res2.data)
    commit('setUserInfo', res3)
    console.log(res3)
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
